<?php
/**
 * Description: 获取公告列表
 * User: devforma
 * Date: 16/6/6
 * Time: 10:26
 */

class GetAnnounces implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);
        
        if (!empty($queryArgs['announce_id'])) {
            $announceId = intval($queryArgs['announce_id']);
        } else {
            $announceId = 0;
        }

        $list = $this->getAnnounceList($queryArgs['user_id'], $announceId);

        return genOutput(1, ['announces' => $list]);
    }

    /**
     * 获取公告列表
     *
     * @param int $userId 用户id
     * @param int $announceId 单个公告id
     * @return array
     */
    private function getAnnounceList($userId, $announceId = 0) {
        global $uddb, $cmsdb;

        if ($announceId == 0) {
            //获取所有公告
            $now = date('Y-m-d H:i:s');
            $all = (array)$cmsdb->getResults('SELECT * FROM `data_primary_announce` WHERE `publish_date`<=:date ORDER BY `publish_date` DESC', [':date' => $now]);
        } else {
            $all = (array)$cmsdb->getResults('SELECT * FROM `data_primary_announce` WHERE `id`=:id', [':id' => $announceId]);
        }

        //获取该用户已读公告
        $readList = (array)$uddb->getCol('SELECT `announce_id` FROM `history_user_announce` WHERE `user_id`=:uid', [':uid' => $userId]);

        $results = [];
        foreach ($all as $item) {
            $data = [
                'id'           => (int)$item->id,
                'title'        => $item->title,
                'content'      => $item->content,
                'publish_date' => $item->publish_date,
                'is_read'      => false
            ];

            //如果该公告已读
            if (in_array($item->id, $readList, true)) {
                $data['is_read'] = true;
            }

            $results[] = $data;
        }

        return $results;
    }
}